GetApiUrl = function(url) {
	return "http://localhost:8088/" + url;
};
GetLocalUrl = function(url) {
	return "http://127.0.0.1:8020/UI/View/" + url + ".html";
};

//Get请求
LocalGet = function(url, callback, async) {
	$.ajax({
		type: "get",
		url: url,
		data: {},
		dataType: "json",
		async: async == false ? false : true,
		xhrFields: {
			withCredentials: true
		},
		success: function(data) {
			if(data.state == '401') {
				Msg(data.msg, 2);
				return false;
			}
			callback(data);
		},
		error: function(data) {
			layer.msg(data.msg);
		}

	});
}
//Get请求
HttpGet = function(url, callback, async) {
	$.ajax({
		type: "get",
		url: GetApiUrl(url),
		data: {},
		dataType: "json",
		headers:IsNull($.cookie("Authorization")) ? null : {
			'Authorization': $.cookie("Authorization")
		},
		async: async == false ? false : true,
		xhrFields: {
			withCredentials: true
		},
		success: function(data) {
			if(data.state == '401') {
				Msg(data.msg, 2);
				return false;
			}
			callback(data);
		},
		error: function(data) {
			layer.msg(data.msg);
		}

	});
}
//Post请求
HttpPost = function(url, postdata, callback, async) {
	$.ajax({
		type: "post",
		contentType: "application/json;charset=utf-8",
		headers: IsNull($.cookie("Authentication")) ? null : {
			'Authorization': $.cookie("Authentication")
		},
		url: GetApiUrl(url),
		data: postdata,
		dataType: "json",
		async: async == false ? false : true,
		xhrFields: {
			withCredentials: true
		},
		success: function(data) {
			callback(data);
		},
		error: function(data) {
			layer.msg(data.msg);
		}

	});
}

//ajax加载页面
$.fn.HttpLoad = function(url, params, callback) {
	var ele = $(this);
	$.ajax({
		type: "get",
		url: GetLocalUrl(url),
		async: false,
		dataType: "html",
		beforeSend: function(xhr) {
			//设置url历史记录
			if(IsNull($.session.get('url_history'))) {
				var histories = url;
				$.session.set('url_history', histories);
			} else {
				var histories = $.session.get('url_history');
				histories = histories + "," + url;
				$.session.set('url_history', histories);
			}
		},
		success: function(data) {
			if(!IsNull(callback())) {
				callback();
			}
			//将要传递的参数放到隐藏的input中
			if(params != null) {
				$.each(params, function(k, v) {
					data += "<input type='hidden' name='"+ k +"' value='"+ v +"'>";
				});
			}

			//			//如果是数组
			//			if(params instanceof Array && params != null){
			//				$.each(params,function(k,v){
			//					$(data).find("input[id='"+ k +"']").val(v);
			//					console.log($(data).find("input[id='"+ k +"']").val())
			//				});
			//			}
			//			//如果是对象
			//			if(params instanceof Object && params != null){
			//					console.log(params.keys);
			//
			//				$(data).find("input[id='"+ params.keys +"']").val(params.Value);
			//				console.log($(data).find("input[id='"+ params.Name +"']").val())
			//			}
			//如果是单个对象
			$(ele).html(data);
		}
	});
}

//判断对象是否为空 ture or false
IsNull = function(obj) {
	if(obj == null || obj == "" || obj == "undefined")
		return true;
	else return false;
}

//获取Url参数值,传入参数名称
QueryUrlValue = function(name) {
	var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
	if(result == null || result.length < 1) {
		return "";
	}
	return result[1];
}

Msg = function(content, type) {
	top.layer.msg(content, {
		icon: type
	});
}

//提交表单
$.fn.SubmitForm = function(url) {
	$(this).click(function() {
		var params = $('form').serializeArray();
		var postdata = {};
		$.each(params, function(i, v) {
			postdata[v.name] = v.value;
		});
		//密码MD5加密
		postdata.password = SHA1.hex_sha1(postdata.password)
		//postdata.password = $.md5(postdata.password);

		var postData = JSON.stringify(postdata)
		HttpPost(url, postData, function(data) {
			if(data.code == "200") {
				Msg(data.message, 1);
				//返回上一个页面
				var histories = $.session.get("url_history").split(",");
				LoadContent(histories[histories.length - 2]);
			} else if(data.code == "-1") {
				Msg(data.message, 2);
			}
		});
		return false;
	});
}

//返回上一级事件
$.fn.BackPage = function() {
	$(this).click(function() {
		var histories = $.session.get("url_history").split(",");
		LoadContent(histories[histories.length - 2]);
	});
}

//查询返回的数据放到table中
$.fn.SetForm = function(url){
	HttpGet(url,function(data){
		console.log(data.data.email)
	},false)
}

/**
 * 内容区域加载页面
 * @param {Object} url
 */
let NowPage;
const LoadContent = function(url, notload, data) {
	if(notload != false) {
		$.AMUI.progress.start();
	}
	$("#ContentArea").HttpLoad(url, data, function() {
		NowPage = url;

		//左菜单显示激活当前所在页面
		const activeNowPage = function() {
			//清除掉所有已经激活的菜单
			const clear = function() {
				$(".sidebar-nav-link a").removeClass("sub-active");
				$(".sidebar-nav-link a").removeClass("active");
			};

			//激活当前菜单
			const active = function() {
				$(".sidebar-nav-link").each(function(k, v) {
					if(NowPage == $(v).data("url")) {
						$(v).find("a:first").addClass("sub-active");
						$(v).parent().parent().find("a[class='sidebar-nav-sub-title']").addClass("active");
					}
				});
			};
			clear();
			active();
		};
		activeNowPage();

		$.AMUI.progress.done();
	});

}

/**
 * 初始化页面
 * 包括一些事件的加载
 */
const InitPage = {
	/**
	 * 初始化首页
	 */
	LoadIndex: function(url) {
		$.AMUI.progress.start();
		InitPage.LoadLeftMenu();
		InitPage.LoadPageEvents();
		LoadContent("Home/index");
	},

	/**
	 * 加载页面的各种事件 如菜单的点击等等
	 */
	LoadPageEvents: function() {
		// 侧边菜单开关
		const autoLeftNav = function() {
			$('.tpl-header-switch-button').on('click', function() {
				if($('.left-sidebar').is('.active')) {
					if($(window).width() > 1024) {
						$('.tpl-content-wrapper').removeClass('active');
					}
					$('.left-sidebar').removeClass('active');
				} else {

					$('.left-sidebar').addClass('active');
					if($(window).width() > 1024) {
						$('.tpl-content-wrapper').addClass('active');
					}
				}
			})

			if($(window).width() < 1024) {
				$('.left-sidebar').addClass('active');
			} else {
				$('.left-sidebar').removeClass('active');
			}
		}
		autoLeftNav();
		$(window).resize(function() {
			autoLeftNav();
		});

		//		// 风格切换
		//		$('.tpl-skiner-toggle').on('click', function() {
		//			$('.tpl-skiner').toggleClass('active');
		//		})
		//
		//		$('.tpl-skiner-content-bar').find('span').on('click', function() {
		//			$('body').attr('class', $(this).attr('data-color'))
		//			saveSelectColor.Color = $(this).attr('data-color');
		//			// 保存选择项
		//			storageSave(saveSelectColor);
		//		})
		//
		// 侧边菜单
		$('.sidebar-nav-sub-title').on('click', function() {
			$(this).siblings('.sidebar-nav-sub').slideToggle(80)
				.end()
				.find('.sidebar-nav-sub-ico').toggleClass('sidebar-nav-sub-ico-rotate');
		})
	},

	/**
	 * 加载左菜单
	 */
	LoadLeftMenu: function() {
		let url = "Module.json";
		LocalGet(url, function(ModuleDatas) {
			let html = '';
			$.each(ModuleDatas, function(index, ModuleData) {
				html += '<li class="sidebar-nav-link">';
				html += '<a href="javascript:;" class="sidebar-nav-sub-title">' +
					'<i class="am-icon-' + ModuleData.Icon + ' sidebar-nav-link-logo"></i>' + ModuleData.Text +
					'<span class="am-icon-chevron-down am-fr am-margin-right-sm sidebar-nav-sub-ico"></span>' +
					'</a>';
				if(ModuleData.Child != null) {
					html += '<ul class="sidebar-nav sidebar-nav-sub">';
					$.each(ModuleData.Child, function(index, ModuleData) {
						html += '<li data-url="' + ModuleData.Url + '" class="sidebar-nav-link">' +
							'<a href="#" onclick="LoadContent(\'' + ModuleData.Url + '\',true)">' +
							'<span class="am-icon-angle-right sidebar-nav-link-logo"></span> ' + ModuleData.Text +
							'</a>' +
							'</li>';
					});
					html += '</ul>';
				}
				html += '</li>';
			});
			$("#MenuArea").html(html);
		}, false);
	}
}

/**
 * SHA1算法
 */
var SHA1 = {
	hexcase: 0,
	b64pad: "",
	chrsz: 8,
	hex_sha1: function(s) {
		return SHA1.binb2hex(SHA1.core_sha1(SHA1.str2binb(s), s.length * SHA1.chrsz));
	},
	binb2hex: function(binarray) {
		var hex_tab = SHA1.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
		var str = "";
		for(var i = 0; i < binarray.length * 4; i++) {
			str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
		}
		return str;
	},
	core_sha1: function(x, len) {
		/* append padding */
		x[len >> 5] |= 0x80 << (24 - len % 32);
		x[((len + 64 >> 9) << 4) + 15] = len;
		var w = Array(80);
		var a = 1732584193;
		var b = -271733879;
		var c = -1732584194;
		var d = 271733878;
		var e = -1009589776;
		for(var i = 0; i < x.length; i += 16) {
			var olda = a;
			var oldb = b;
			var oldc = c;
			var oldd = d;
			var olde = e;
			for(var j = 0; j < 80; j++) {
				if(j < 16) w[j] = x[i + j];
				else w[j] = SHA1.rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
				var t = SHA1.safe_add(SHA1.safe_add(SHA1.rol(a, 5), SHA1.sha1_ft(j, b, c, d)), SHA1.safe_add(SHA1.safe_add(e, w[j]), SHA1.sha1_kt(j)));
				e = d;
				d = c;
				c = SHA1.rol(b, 30);
				b = a;
				a = t;
			}
			a = SHA1.safe_add(a, olda);
			b = SHA1.safe_add(b, oldb);
			c = SHA1.safe_add(c, oldc);
			d = SHA1.safe_add(d, oldd);
			e = SHA1.safe_add(e, olde);
		}
		return Array(a, b, c, d, e);
	},
	str2binb: function(str) {
		var bin = Array();
		var mask = (1 << SHA1.chrsz) - 1;
		for(var i = 0; i < str.length * SHA1.chrsz; i += SHA1.chrsz)
			bin[i >> 5] |= (str.charCodeAt(i / SHA1.chrsz) & mask) << (24 - i % 32);
		return bin;
	},
	safe_add: function(x, y) {
		var lsw = (x & 0xFFFF) + (y & 0xFFFF);
		var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
		return(msw << 16) | (lsw & 0xFFFF);
	},
	rol: function(num, cnt) {
		return(num << cnt) | (num >>> (32 - cnt));
	},
	sha1_ft: function(t, b, c, d) {
		if(t < 20) return(b & c) | ((~b) & d);
		if(t < 40) return b ^ c ^ d;
		if(t < 60) return(b & c) | (b & d) | (c & d);
		return b ^ c ^ d;
	},
	sha1_kt: function(t) {
		return(t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
	}
}

/**
 * JquerySession
 */
;
(function($) {
	$.session = {
		_id: null,
		_cookieCache: undefined,
		_init: function() {
			if(!window.name) {
				window.name = Math.random();
			}
			this._id = window.name;
			this._initCache();
			var matches = (new RegExp(this._generatePrefix() + "=([^;]+);")).exec(document.cookie);
			if(matches && document.location.protocol !== matches[1]) {
				this._clearSession();
				for(var key in this._cookieCache) {
					try {
						window.sessionStorage.setItem(key, this._cookieCache[key]);
					} catch(e) {};
				}
			}
			document.cookie = this._generatePrefix() + "=" + document.location.protocol + ';path=/;expires=' + (new Date((new Date).getTime() + 120000)).toUTCString();
		},
		_generatePrefix: function() {
			return '__session:' + this._id + ':';
		},
		_initCache: function() {
			var cookies = document.cookie.split(';');
			this._cookieCache = {};
			for(var i in cookies) {
				var kv = cookies[i].split('=');
				if((new RegExp(this._generatePrefix() + '.+')).test(kv[0]) && kv[1]) {
					this._cookieCache[kv[0].split(':', 3)[2]] = kv[1];
				}
			}
		},
		_setFallback: function(key, value, onceOnly) {
			var cookie = this._generatePrefix() + key + "=" + value + "; path=/";
			if(onceOnly) {
				cookie += "; expires=" + (new Date(Date.now() + 120000)).toUTCString();
			}
			document.cookie = cookie;
			this._cookieCache[key] = value;
			return this;
		},
		_getFallback: function(key) {
			if(!this._cookieCache) {
				this._initCache();
			}
			return this._cookieCache[key];
		},
		_clearFallback: function() {
			for(var i in this._cookieCache) {
				document.cookie = this._generatePrefix() + i + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
			}
			this._cookieCache = {};
		},
		_deleteFallback: function(key) {
			document.cookie = this._generatePrefix() + key + '=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
			delete this._cookieCache[key];
		},
		get: function(key) {
			return window.sessionStorage.getItem(key) || this._getFallback(key);
		},
		set: function(key, value, onceOnly) {
			try {
				window.sessionStorage.setItem(key, value);
			} catch(e) {}
			this._setFallback(key, value, onceOnly || false);
			return this;
		},
		'delete': function(key) {
			return this.remove(key);
		},
		remove: function(key) {
			try {
				window.sessionStorage.removeItem(key);
			} catch(e) {};
			this._deleteFallback(key);
			return this;
		},
		_clearSession: function() {
			try {
				window.sessionStorage.clear();
			} catch(e) {
				for(var i in window.sessionStorage) {
					window.sessionStorage.removeItem(i);
				}
			}
		},
		clear: function() {
			this._clearSession();
			this._clearFallback();
			return this;
		}
	};
	$.session._init();
})(jQuery);

/**
 * JqueryCookie
 */
;
(function(factory) {
	if(typeof define === 'function' && define.amd) {
		// AMD
		define(['jquery'], factory);
	} else if(typeof exports === 'object') {
		// CommonJS
		factory(require('jquery'));
	} else {
		// Browser globals
		factory(jQuery);
	}
}(function($) {
	var pluses = /\+/g;

	function encode(s) {
		return config.raw ? s : encodeURIComponent(s);
	}

	function decode(s) {
		return config.raw ? s : decodeURIComponent(s);
	}

	function stringifyCookieValue(value) {
		return encode(config.json ? JSON.stringify(value) : String(value));
	}

	function parseCookieValue(s) {
		if(s.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape...
			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
		}
		try {
			// Replace server-side written pluses with spaces.
			// If we can't decode the cookie, ignore it, it's unusable.
			// If we can't parse the cookie, ignore it, it's unusable.
			s = decodeURIComponent(s.replace(pluses, ' '));
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

	function read(s, converter) {
		var value = config.raw ? s : parseCookieValue(s);
		return $.isFunction(converter) ? converter(value) : value;
	}
	var config = $.cookie = function(key, value, options) {
		// Write
		if(value !== undefined && !$.isFunction(value)) {
			options = $.extend({}, config.defaults, options);
			if(typeof options.expires === 'number') {
				var days = options.expires,
					t = options.expires = new Date();
				t.setTime(+t + days * 864e+5);
			}
			return(document.cookie = [
				encode(key), '=', stringifyCookieValue(value),
				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
				options.path ? '; path=' + options.path : '',
				options.domain ? '; domain=' + options.domain : '',
				options.secure ? '; secure' : ''
			].join(''));
		}
		// Read
		var result = key ? undefined : {};
		var cookies = document.cookie ? document.cookie.split('; ') : [];
		for(var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decode(parts.shift());
			var cookie = parts.join('=');
			if(key && key === name) {
				result = read(cookie, value);
				break;
			}
			if(!key && (cookie = read(cookie)) !== undefined) {
				result[name] = cookie;
			}
		}
		return result;
	};
	config.defaults = {};
	$.removeCookie = function(key, options) {
		if($.cookie(key) === undefined) {
			return false;
		}
		$.cookie(key, '', $.extend({}, options, {
			expires: -1
		}));
		return !$.cookie(key);
	};
}));